<?php

namespace app\services;

use app\traits\Page;
use EasyWeChat\Factory;
use plugin\admin\app\model\Store;
use plugin\admin\app\model\StoreApply;
use plugin\admin\app\model\StoreCategory;
use plugin\admin\app\model\StoreContact;
use plugin\admin\app\model\StoreImage;
use support\Db;
use Webman\Config;

class StoreService
{
    public static function list($categoryId = 0, $page = 1, $length = 10, $longitude = 0, $latitude = 0)
    {
        $offset = ($page - 1) * $length;

        if ($categoryId) {
            $query = Store::where('category_id', $categoryId);
        } else {
            $query = new Store();
        }

        $totalCount = (clone $query)->count();
        $stores = (clone $query)->select(['id', 'thumb', 'company_name', 'desc', 'name', 'business_start_time', 'business_end_time', 'province', 'city', 'district', 'address', 'longitude', 'latitude', 'contact_mobile', Db::raw("(6371 * acos(cos(radians($latitude)) * cos(radians(latitude)) * cos(radians(longitude) - radians($longitude)) + sin(radians($latitude)) * sin(radians(latitude)))) as distance")])->offset($offset)->limit($length)->orderBy('distance')->get()->toArray();

        foreach ($stores as $key=>$store) {
            $stores[$key]['thumb'] = full_url($store['thumb']);
            $stores[$key]['desc'] = strip_tags($store['desc']);
        }

        return Page::wrap($totalCount, $page, $length, $stores);
    }

    public static function detail($id)
    {
        $store = Store::select(['id', 'content', 'desc', 'name', 'business_start_time', 'thumb', 'business_end_time', 'province', 'city', 'district', 'address', 'longitude', 'latitude', 'contact_mobile', 'contact_name'])->where('id', $id)->first();

        if (! $store) {
            throw new \Exception('不存在的商行');
        }

        $images = StoreImage::select(['img_url'])->where('store_id', $id)->get()->toArray();
        $store['content'] = str_replace('src="/', 'src="' . getenv('APP_URL') . '/', $store['desc']);

        $store['images'] = [full_url($store['thumb'])];
//        $store['content'] = json_decode($store['content'], true);
        $store['images'] += array_column($images, 'img_url');

        return $store;
    }

    public static function contact($data)
    {
        if (StoreContact::where('store_id', $data['id'])->where('contact_name', $data['name'])->where('contact_mobile', $data['mobile'])->count()) {
            throw new \Exception('你已提交申请');
        }

        StoreContact::insert([
            'store_id' => $data['id'],
            'contact_name' => $data['name'],
            'contact_mobile' => $data['mobile'],
            'created_time' => date('Y-m-d H:i:s'),
        ]);
    }

    public static function apply($data)
    {
        if (StoreApply::where('user_id', get_user_id())->where('status', StoreApply::UNPROCESS)->count() > 0) {
            throw new \Exception('已经申请，请耐心等候审核');
        }

        $data['user_id'] = get_user_id();
        $data['status'] = StoreApply::UNPROCESS;
        $data['created_time'] = date('Y-m-d H:i:s');
        $data['images'] = json_encode($data['images'], JSON_UNESCAPED_UNICODE);
        return StoreApply::insertGetId($data);
    }

    public static function applyDetail()
    {
        $storeApply = StoreApply::where('user_id', get_user_id())->orderByDesc('created_time')->first();

        if (!$storeApply) {
            throw new \Exception('未申请');
        }

        $storeApply['status_text'] = StoreApply::getStatusText($storeApply['status']);

        return $storeApply;
    }

    public static function liveRooms($page, $length)
    {
        $offset = ($page - 1) * $length;
        $config = Config::get('wechat');
        $app = Factory::miniProgram($config);

        $result = $app->live->getRooms($offset, $length);

        if ($result['errcode'] == 0) {
            return Page::wrap($result['total'], $page, $length, $result['room_info']);
        }

        return [];
    }

    public static function categories($showIsSystem = 0)
    {
        if ($showIsSystem) {
            return StoreCategory::all()->toArray();
        }

        return StoreCategory::where('is_system', 0)->get()->toArray();
    }
}